﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ARS.Control.Common.EntityManage;
using ARS.Control.Custom.Entity.Fields;
using ARS.Control.Custom.Entity.Forms;
using ARS.Control.Custom.Entity.Model;

namespace ARS.Control.Custom.Entity.Widget
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:EntityMappingPanel runat=server></{0}:EntityMappingPanel>")]
    public class EntityMappingPanel : EntityControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        public EntityMappingPanel()
        {
            base.type = EntityModel.TYPE_MAPPED;
        }

        /// <summary>
        /// 获取form属性field的值
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        protected string GetFormFieldVale(Fields.Field form)
        {
            if (form is ChoicesField)
            {
                ChoicesField field = form as ChoicesField;
                ARS.PublicTool.DataHandle.ChoicesHelper choicesHelper = new PublicTool.DataHandle.ChoicesHelper();
                try
                {
                    return choicesHelper.GetValueFromChoices(field.Choices, field.Value.ToString());
                }
                catch (Exception)
                {

                    return null;
                }
                //return field.Widget.GetInputValue().ToString();
                //return Forms.ChoicesForm.ChoicesHelper.GetValueFromChoices(field.Choices, field.Value.ToString());
            }            
            else if (form is UserField)
            {
                ARS.Control.Interface.IUser user = Factory.UserFactory.CreateUser();
                return user.GetUserShowInfo(form);
            }
            else if (form is ForeignKeyField)
            {
                string sql = null;
                ForeignKeyField field = null;
                
                if (form is ChoicesDialogField)
                {

                    ChoicesDialogField dialog = form as ChoicesDialogField;
                    if (dialog.ShowQuerySql == null)
                    {
                        if (form.Value == null)
                        {
                            return null;
                        }
                        string value = form.Value.ToString();
                        string whereValue = string.Join(",", from str in value.Split('|') where !String.IsNullOrEmpty(str) select str);
                        field = form as ForeignKeyField;
                        sql = string.Format("select {0} from {1} where {2} in ({3})",
                            field.SelectDbSelectConfig.DataTextField, field.SelectDbSelectConfig.TableName,
                            field.SelectDbSelectConfig.DataValueField, whereValue);
                    }
                    else
                    {
                        sql = string.Format(dialog.ShowQuerySql, EntityTableInfo.KeyInfo.Value);
                    }
                }
                else
                {
                    if (form.Value == null)
                    {
                        return null;
                    }
                    field = form as ForeignKeyField;
                    sql = string.Format("select {0} from {1} where {2}={3}",
                       field.SelectDbSelectConfig.DataTextField, field.SelectDbSelectConfig.TableName,
                       field.SelectDbSelectConfig.DataValueField, field.Value);
                }
                if (!string.IsNullOrEmpty(sql))
                {
                    DataTable dt = Factory.DbFactory.DbProvider.Query(sql).Tables[0];
                    return string.Join(",", from row in dt.AsEnumerable() select row[0]);
                }
            }
            else if (form is DecimalField)
            {

                Func<decimal, string> Getstring = (decimalValue) =>
                {
                   return double.Parse(decimalValue.ToString()).ToString();
                };
                string value = form.Value.ToString();
                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }
                else
                {
                    return Getstring(decimal.Parse(value));
                }
                
            }
            else if (form.Value == null)
            {

            }
            else
            {
                return form.Value.ToString();
            }
            return null;
        }

        public delegate System.Web.UI.Control GetControlDelegate(Fields.Field form);
        /// <summary>
        /// 获取控件回调
        /// </summary>
        public event GetControlDelegate GetControlEvent;

        /// <summary>
        /// 实体数据到控件
        /// </summary>
        public override void EntityToControl()
        {
            foreach (var column in EntityTableInfo.FieldList)
            {
                //object value = column.Field.Value;            
                if (column.Value == null)
                {
                    continue;
                }
                string value = this.GetFormFieldVale(column);
                //string name = ControlIdStart+column.Field.Db_Field_Name; 
                //获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
                //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
                //if (value.GetType() == typeof(int))
                //{
                //    //进行你想要的操作
                //    //Response.Write(name);
                //}

                System.Web.UI.Control control;
                if (this.GetControlEvent == null)
                {
                    control = this.FindControl(column.Db_Field_Name);
                }
                else
                {
                    control = this.GetControlEvent(column);
                }
                // = this.FindControl(GetControlEvent(column));//this.FindControl(name);
                if (control == null)
                {
                    continue;
                }
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.Text = value.ToString();
                }
                if (control is DropDownList)
                {
                    DropDownList drop = (DropDownList)control;
                    drop.SelectedValue = value.ToString();
                }
                if (control is Literal)
                {
                    Literal literal = (Literal)control;
                    literal.Text = value.ToString();
                }
                if (control is Image)
                {
                    Image image = (Image) control;
                    image.ImageUrl = value.ToString();
                }
            }


        }

        /// <summary>
        /// 控件的开头
        /// </summary>
        //public string ControlIdStart
        //{
        //    get;
        //    set;
        //}

        /// <summary>
        /// 控件数据到实体
        /// </summary>
        public override void ControlToEntity()
        {

            //Type type = Entity.GetType();
            foreach (System.Web.UI.Control control in this.Controls)
            {
                string value = null;
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    value = textBox.Text;
                }
                else if (control is DropDownList)
                {
                    DropDownList drop = (DropDownList)control;
                    value = drop.SelectedValue;
                }
                else if (control is Form)
                {
                    Form f = (Form) control;
                    value = f.GetInputValue().ToString();
                }
                else if (control is ARS.Control.Custom.SelectLinkage.Widget.SelectLinkage)
                {
                    ARS.Control.Custom.SelectLinkage.Widget.SelectLinkage selectLinkage =
                        (ARS.Control.Custom.SelectLinkage.Widget.SelectLinkage) control;
                    value = selectLinkage.GetInputValue();
                }
                else if (control is HiddenField)
                {
                    HiddenField hiddenField = (HiddenField) control;
                    value = hiddenField.Value;
                }
                else
                {
                    continue;
                }
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }
                string fieldName = control.ID;
                //if (string.IsNullOrEmpty(ControlIdStart))
                //{
                //    fieldName = control.ID;
                //}
                //else
                //{
                //    fieldName = control.ID.Replace(ControlIdStart, "");
                //}

                var form = (from item in EntityTableInfo.FieldList
                    where item.Db_Field_Name == fieldName
                    select item).ToList();
                if (form.Count == 1)
                {
                    form[0].Value = value;
                }
                //object objValue;
                //var field = TypeModel.GetProperty(fieldName);
                //if (field == null)
                //{
                //    continue;
                //}
                //Type fieldType = field.PropertyType;
                ////Type t = typeof (Nullable<>);
                //if (fieldType.Remark == typeof(Nullable<>).Remark)
                //{
                //    objValue = value.ConvertTo<Nullable<int>>();
                //}
                //else
                //{
                //    objValue = Convert.ChangeType(value, fieldType);
                //}
                ////object objValue = value.ConvertTo<Nullable<int>>();// Convert.ChangeType(value,fieldType )
                //field.SetValue(Entity, objValue, null);
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            base.RenderContents(output);
        }
    }
}
